package com.lucas.filter;

import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


import java.util.HashMap;
import java.util.Map;

/**
 *
 * 防止刷爆,5秒钟之内不能重复请求
 * @program: spring_cloud_lagou_homework
 * @author: lucasLu
 **/
@Slf4j
@Component
public class IPFilter implements GlobalFilter, Ordered {
    private static Map<String,Long> map = new HashMap<>();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取request,response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String clientIp = request.getRemoteAddress().getHostString();
        if(map.containsKey(clientIp)){
            Long aLong = map.get(clientIp);
            long now = System.currentTimeMillis();
            //五秒内重复,扔掉
            if((now-aLong)<5000){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                log.info("======> ip:"+clientIp+"在5秒重复发送,将拒绝访问");
                String data ="Request be denied";
                DataBuffer dataBuffer = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(dataBuffer));
            }else {
                map.put(clientIp,now);
                return   chain.filter(exchange);
            }
        }
        map.put(clientIp,System.currentTimeMillis());
        return   chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
